import datetime

from django.db import models
from django.db.models import Max
from users.models import UserInfo

GENDER = (
    ("男", "男"),
    ("女", "女")
)
POST = (
    (1, "主办律师"),
    (2, "辅助律师"),
    (3, "客户经理"),
    (4, "案件研讨"),
    (5, "办案费"),
    (6, "商务费"),
    (7, "咨询费"),
)

CASE_CATEGORY = (
    (1, "民事案件"),
    (2, "刑事案件"),
    (3, "行政案件"),
    (4, "刑附民案件"),
    (5, "刑事自诉案件"),
    (6, "法律仲裁"),
)

ACCOUNT_TYPE = (
    (0, '未收款'),
    (1, '现金'),
    (2, '银行'),
)


class Job(models.Model):
    """职务"""
    id = models.IntegerField(verbose_name='职务编号', primary_key=True)
    name = models.CharField(verbose_name='职务名称', max_length=50)

    class Meta:
        verbose_name = '职务名称'
        verbose_name_plural = verbose_name
        ordering = ['id']

    def __str__(self):
        return self.name


class AccountCode(models.Model):
    """财务科目编码"""
    code = models.CharField(verbose_name='科目编码', max_length=12, primary_key=True)
    name = models.CharField(verbose_name="名称", max_length=32)

    class Meta:
        verbose_name = '财务科目编码'
        verbose_name_plural = verbose_name
        ordering = ['code']

    def __str__(self):
        return self.name


class AccountTitle(models.Model):
    """会计科目"""
    name = models.CharField(verbose_name="名称", max_length=32)
    desc = models.CharField(verbose_name='说明', max_length=64, blank=True, null=True)
    parent = models.ForeignKey('self', verbose_name='父项', related_name='children', blank=True, null=True, db_constraint=False, on_delete=models.SET_NULL)
    code = models.CharField(verbose_name='科目编码', max_length=12, blank=True, null=True)
    update_at = models.DateTimeField(verbose_name='创建时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '会计科目'
        verbose_name_plural = verbose_name
        ordering = ['id']


class Employee(models.Model):
    name = models.CharField(verbose_name='姓名', max_length=24)
    gender = models.CharField(verbose_name='性别', max_length=4, choices=GENDER, blank=True, null=True)
    telephone = models.CharField(verbose_name='手机', max_length=16, blank=True, null=True)
    id_card = models.CharField(verbose_name='身份证号', max_length=32, blank=True, null=True)
    job = models.ForeignKey(to='Job', verbose_name='职务', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    update_at = models.DateTimeField(verbose_name='创建时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '员工信息'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class Customer(models.Model):
    name = models.CharField(verbose_name='姓名', max_length=64)
    gender = models.CharField(verbose_name='性别', max_length=4, choices=GENDER, blank=True, null=True)
    case_name = models.CharField(verbose_name='案件名称', max_length=128, blank=True, null=True)
    case_category = models.IntegerField(verbose_name='案件类型', choices=CASE_CATEGORY, blank=True, null=True)
    telephone = models.CharField(verbose_name='手机号码', max_length=16, blank=True, null=True)
    id_card = models.CharField(verbose_name='身份证号', max_length=32, blank=True, null=True)
    address = models.CharField(verbose_name='地址', max_length=128, blank=True, null=True)
    help_code = models.CharField(verbose_name='助记码', max_length=64, blank=True, null=True)
    update_at = models.DateTimeField(verbose_name='创建时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '客户资料'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class CasePerson(models.Model):
    """案件相关人员"""
    customer = models.ForeignKey(Customer, verbose_name='案件名称', related_name="persons", on_delete=models.CASCADE, db_constraint=False)
    name = models.CharField(verbose_name='姓名', max_length=24)
    gender = models.CharField(verbose_name='性别', max_length=4, choices=GENDER, blank=True, null=True)
    telephone = models.CharField(verbose_name='手机号码', max_length=16, blank=True, null=True)
    id_card = models.CharField(verbose_name='身份证号', max_length=32, blank=True, null=True)
    update_at = models.DateTimeField(verbose_name='创建时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '案件相关人员'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class CaseLawyer(models.Model):
    """案件律师"""
    customer = models.ForeignKey(Customer, verbose_name='案件名称', related_name="lawyers", on_delete=models.CASCADE, null=True, db_constraint=False)
    employee = models.ForeignKey(Employee, verbose_name='律师', related_name="employees", on_delete=models.CASCADE, null=True, db_constraint=False)
    post = models.IntegerField(verbose_name='岗位', choices=POST, blank=True, null=True)
    # ratio = models.IntegerField(verbose_name='利润比例(%)', blank=True, null=True)
    update_at = models.DateTimeField(verbose_name='创建时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.employee.name

    class Meta:
        verbose_name = '案件律师'
        verbose_name_plural = verbose_name
        ordering = ["customer", "post"]


class Bank(models.Model):
    """银行信息"""
    account = models.CharField(verbose_name='银行账号', max_length=64)
    money = models.FloatField(verbose_name='现金额', default=0)
    desc = models.CharField(verbose_name='备注', max_length=128, blank=True, null=True)

    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.account

    class Meta:
        verbose_name = '银行信息'
        verbose_name_plural = verbose_name
        ordering = ["id"]


class SaleOrder(models.Model):
    """销售订单1"""
    order_no = models.CharField(verbose_name='单据号', max_length=24, blank=True, null=True)
    order_time = models.DateField(verbose_name='单据时间', blank=True, null=True)
    customer = models.ForeignKey(Customer, verbose_name='客户名称', on_delete=models.SET_NULL, null=True, db_constraint=False)
    case_name = models.CharField(verbose_name='案件名称', max_length=128, blank=True, null=True)
    telephone = models.CharField(verbose_name='手机号', max_length=24, blank=True, null=True)
    acc_title = models.ForeignKey(AccountTitle, verbose_name='科目', on_delete=models.SET_NULL, null=True, db_constraint=False)
    recv_money = models.FloatField(verbose_name='应收金额', default=0, blank=True, null=True)
    paid_money = models.FloatField(verbose_name='实收金额', default=0, blank=True, null=True)
    payment_money = models.FloatField(verbose_name='支出金额', default=0, blank=True, null=True)
    account_type = models.ForeignKey(Bank, verbose_name='收款账号', on_delete=models.SET_NULL, null=True, db_constraint=False)
    desc = models.CharField(verbose_name='备注', max_length=100, blank=True, null=True)
    bill = models.CharField(verbose_name='发票', max_length=50, blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='录入人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    handler = models.ForeignKey(Employee, verbose_name='经办人',  related_name='orders', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        if self.customer:
            return '{}[{}]'.format(self.customer.name, self.order_no)
        else:
            return self.order_no

    class Meta:
        verbose_name = '销售订单'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        year = datetime.datetime.now().strftime('XS%Y%m')
        max_code = cls.objects.filter(order_no__startswith=year).aggregate(max_code=Max("order_no"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(year, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(year, num)
            return code

    def save(self, *args, **kwargs):
        if not self.order_no:
            order_no = self.__class__.get_max_code()
            self.order_no = order_no
        return super().save(*args, **kwargs)


class Receipt(models.Model):
    """收款单1"""
    order_no = models.CharField(verbose_name='单号', max_length=24, blank=True, null=True)
    sale_order = models.ForeignKey(SaleOrder, verbose_name='销售单', related_name="receipts", on_delete=models.CASCADE, null=True, db_constraint=False)
    case_name = models.CharField(verbose_name='案件名称', max_length=128, blank=True, null=True)
    telephone = models.CharField(verbose_name='手机号', max_length=24, blank=True, null=True)
    recv_money = models.FloatField(verbose_name='应收金额', default=0, blank=True, null=True)
    paid_money = models.FloatField(verbose_name='实收金额', default=0, blank=True, null=True)
    acc_title = models.ForeignKey(AccountTitle, verbose_name='科目', on_delete=models.SET_NULL, null=True, db_constraint=False)
    account_type = models.ForeignKey(Bank, verbose_name='收款账号', on_delete=models.SET_NULL, null=True,
                                     db_constraint=False)
    desc = models.CharField(verbose_name='备注', max_length=100, blank=True, null=True)
    order_time = models.DateField(verbose_name='时间', blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='经手人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    handler = models.ForeignKey(Employee, verbose_name='经办人', related_name='receipts', blank=True, null=True,
                                on_delete=models.SET_NULL, db_constraint=False)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.order_no

    class Meta:
        verbose_name = '收款单'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        year = datetime.datetime.now().strftime('SK%Y%m')
        max_code = cls.objects.filter(order_no__startswith=year).aggregate(max_code=Max("order_no"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(year, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(year, num)
            return code

    def save(self, *args, **kwargs):
        if not self.order_no:
            order_no = self.__class__.get_max_code()
            self.order_no = order_no
        return super().save(*args, **kwargs)


class Expense(models.Model):
    """费用单（废弃）"""
    order_no = models.CharField(verbose_name='单号', max_length=24, blank=True, null=True)
    name = models.CharField(verbose_name='姓名', max_length=24, blank=True, null=True)
    acc_title = models.ForeignKey(AccountTitle, verbose_name='科目', on_delete=models.SET_NULL, null=True, db_constraint=False)
    money = models.FloatField(verbose_name='金额', default=0, blank=True, null=True)
    order_time = models.DateField(verbose_name='费用时间', blank=True, null=True)
    account_type = models.ForeignKey(Bank, verbose_name='付款账号', on_delete=models.SET_NULL, null=True,
                                     db_constraint=False)
    desc = models.CharField(verbose_name='备注', max_length=100, blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='经手人', blank=True, null=True, on_delete=models.SET_NULL)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '费用单'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        year = datetime.datetime.now().strftime('FY%Y%m')
        max_code = cls.objects.filter(order_no__startswith=year).aggregate(max_code=Max("order_no"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(year, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(year, num)
            return code

    def save(self, *args, **kwargs):
        if not self.order_no:
            order_no = self.__class__.get_max_code()
            self.order_no = order_no
        return super().save(*args, **kwargs)


class ProfitRule(models.Model):
    """利润分配规则"""
    position = models.IntegerField(verbose_name='职位', choices=POST)
    ratio = models.IntegerField(verbose_name='利润比例(%)')
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.position

    class Meta:
        verbose_name = '利润分配规则'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class OtherIncome(models.Model):
    """其他收入（废弃）"""
    order_no = models.CharField(verbose_name='单号', max_length=24, blank=True, null=True)
    name = models.CharField(verbose_name='姓名', max_length=24, blank=True, null=True)
    acc_title = models.ForeignKey(AccountTitle, verbose_name='科目', on_delete=models.SET_NULL, null=True, db_constraint=False)
    account_type = models.ForeignKey(Bank, verbose_name='收款账号', on_delete=models.SET_NULL, null=True,
                                     db_constraint=False)
    money = models.FloatField(verbose_name='金额', default=0, blank=True, null=True)
    order_time = models.DateField(verbose_name='时间', blank=True, null=True)
    desc = models.CharField(verbose_name='备注', max_length=100, blank=True, null=True)
    source = models.CharField(verbose_name='收入来源', max_length=100, blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='经手人', blank=True, null=True, on_delete=models.SET_NULL)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.order_no

    class Meta:
        verbose_name = '其他收入'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        year = datetime.datetime.now().strftime('QT%Y%m')
        max_code = cls.objects.filter(order_no__startswith=year).aggregate(max_code=Max("order_no"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(year, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(year, num)
            return code

    def save(self, *args, **kwargs):
        if not self.order_no:
            order_no = self.__class__.get_max_code()
            self.order_no = order_no
        return super().save(*args, **kwargs)


class PaymentOrder(models.Model):
    """利润分配"""
    order_no = models.CharField(verbose_name='编号', max_length=24, blank=True, null=True)
    sale_order = models.ForeignKey(SaleOrder, verbose_name='销售单', related_name="payments", on_delete=models.DO_NOTHING,
                                   null=True, db_constraint=False)
    customer_name = models.CharField(verbose_name='客户名称', max_length=64, blank=True, null=True)
    order_time = models.DateField(verbose_name='时间', blank=True, null=True)
    desc = models.CharField(verbose_name='备注', max_length=100, blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='经手人', blank=True, null=True, on_delete=models.SET_NULL)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.order_no

    class Meta:
        verbose_name = '利润分配'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        year = datetime.datetime.now().strftime('FP%Y%m')
        max_code = cls.objects.filter(order_no__startswith=year).aggregate(max_code=Max("order_no"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(year, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(year, num)
            return code

    def save(self, *args, **kwargs):
        if not self.order_no:
            order_no = self.__class__.get_max_code()
            self.order_no = order_no
        return super().save(*args, **kwargs)


class PaymentDetail(models.Model):
    """付款单"""
    payment = models.ForeignKey(PaymentOrder, verbose_name='付款单', related_name="details", on_delete=models.CASCADE, null=True, db_constraint=False)
    lawyer = models.ForeignKey(Employee, verbose_name='律师', related_name="lawyers", on_delete=models.SET_NULL, null=True, db_constraint=False)
    post = models.IntegerField(verbose_name='职位', choices=POST, blank=True, null=True)
    ratio = models.IntegerField(verbose_name='利润比例(%)', blank=True, null=True)
    acc_title = models.ForeignKey(AccountTitle, verbose_name='科目', on_delete=models.SET_NULL, null=True,
                                  db_constraint=False)
    account_type = models.ForeignKey(Bank, verbose_name='支付账号', on_delete=models.SET_NULL, null=True,
                                     db_constraint=False)
    money = models.FloatField(verbose_name='金额', default=0, blank=True, null=True)
    desc = models.CharField(verbose_name='备注', max_length=100, blank=True, null=True)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.payment.order_no

    class Meta:
        verbose_name = '付款单明细'
        verbose_name_plural = verbose_name
        ordering = ["-payment", "post"]


class PayOrder(models.Model):
    """律师费付款单1"""
    order_no = models.CharField(verbose_name='单号', max_length=24, blank=True, null=True)
    order_time = models.DateField(verbose_name='时间', blank=True, null=True)
    sale_order = models.ForeignKey(SaleOrder, verbose_name='销售单', related_name="pays", on_delete=models.CASCADE, null=True, db_constraint=False)
    person = models.ForeignKey(Employee, verbose_name='姓名', related_name="persons", on_delete=models.SET_NULL, null=True, db_constraint=False)
    acc_title = models.ForeignKey(AccountTitle, verbose_name='科目', on_delete=models.SET_NULL, null=True,
                                  db_constraint=False)
    account_type = models.ForeignKey(Bank, verbose_name='支付账号', on_delete=models.SET_NULL, null=True,
                                     db_constraint=False)
    money = models.FloatField(verbose_name='金额', default=0, blank=True, null=True)
    desc = models.CharField(verbose_name='备注', max_length=100, blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='经手人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    flag = models.BooleanField(verbose_name='支付确认', default=False, blank=True)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.order_no

    class Meta:
        verbose_name = '付款单'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        year = datetime.datetime.now().strftime('P%Y%m')
        max_code = cls.objects.filter(order_no__startswith=year).aggregate(max_code=Max("order_no"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(year, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(year, num)
            return code

    def save(self, *args, **kwargs):
        if not self.order_no:
            order_no = self.__class__.get_max_code()
            self.order_no = order_no
        return super().save(*args, **kwargs)


class Journal(models.Model):
    """流水账"""
    order_no = models.CharField(verbose_name='单据号', max_length=24, blank=True, null=True)
    order_time = models.DateField(verbose_name='单据日期', blank=True, null=True)
    name = models.CharField(verbose_name="用户名称", max_length=128, blank=True, null=True)
    acc_title = models.ForeignKey(AccountTitle, verbose_name='科目', on_delete=models.SET_NULL, null=True,
                                  db_constraint=False)
    account_type = models.ForeignKey(Bank, verbose_name='银行名称', on_delete=models.SET_NULL, null=True,
                                     db_constraint=False)
    account_type_name = models.CharField(verbose_name='银行名称', blank=True, null=True, max_length=64)
    order_type = models.IntegerField(verbose_name="类型", blank=True, null=True, choices=((0, '收入'), (1, '支出')))
    oper_type = models.CharField(verbose_name="操作类型", blank=True, null=True, max_length=128)
    total_money = models.FloatField(verbose_name='总金额', default=0, blank=True, null=True)
    income_money = models.FloatField(verbose_name='收入金额', default=0, blank=True, null=True)
    expense_money = models.FloatField(verbose_name='支出金额', default=0, blank=True, null=True)
    desc = models.CharField(verbose_name='备注', max_length=100, blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='录入人', blank=True, null=True, on_delete=models.SET_NULL)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.order_no

    class Meta:
        verbose_name = '流水账'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class InitAccount(models.Model):
    """初始建账"""
    name = models.CharField(verbose_name="账户名称", max_length=60)
    money = models.FloatField(verbose_name="金额", default=0, blank=True, null=True)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '初始建账'
        verbose_name_plural = verbose_name
        ordering = ["-create_at"]


class HisBank(models.Model):
    """账户历史记录"""
    account_id = models.IntegerField(verbose_name='银行账号ID', blank=True, null=True)
    account_name = models.CharField(verbose_name='银行账号', max_length=64, blank=True, null=True)
    money = models.FloatField(verbose_name='现金额', default=0)
    desc = models.CharField(verbose_name='备注', max_length=128, blank=True, null=True)

    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.account_name

    class Meta:
        verbose_name = '账户历史记录'
        verbose_name_plural = verbose_name
        ordering = ["-create_at"]


class BorrowLend(models.Model):
    """借入借出（废弃）"""
    CATEGORY = (
        (1, '借入'),
        (2, '借出'),
    )
    order_no = models.CharField(verbose_name='单据号', max_length=24, blank=True, null=True)
    person = models.ForeignKey(Employee, verbose_name='姓名', related_name="bl_lists", on_delete=models.SET_NULL, null=True, db_constraint=False)
    money = models.FloatField(verbose_name='金额(元)', default=0, blank=True, null=True)
    account_type = models.ForeignKey(Bank, verbose_name='银行名称', on_delete=models.SET_NULL, null=True,
                                     db_constraint=False)
    category = models.IntegerField(verbose_name='类型', blank=True, null=True, choices=CATEGORY)
    oper_time = models.DateField(verbose_name='借入借出时间', blank=True, null=True)
    desc = models.CharField(verbose_name='备注', max_length=100, blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='经手人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.order_no

    class Meta:
        verbose_name = '借入借出'
        verbose_name_plural = verbose_name
        ordering = ["-create_at"]

    @classmethod
    def get_max_code(cls, category):
        if category == 1:
            year = datetime.datetime.now().strftime('B%Y%m')
        else:
            year = datetime.datetime.now().strftime('L%Y%m')

        max_code = cls.objects.filter(order_no__startswith=year).aggregate(max_code=Max("order_no"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(year, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(year, num)
            return code

    def save(self, *args, **kwargs):
        if not self.order_no:
            order_no = self.__class__.get_max_code(self.category)
            self.order_no = order_no
        return super().save(*args, **kwargs)


class FundBill(models.Model):
    """资金账单(主)"""
    CATEGORY = (
        (0, '费用'),
        (1, '收入'),
        (2, '借入'),
        (3, '借出'),
    )
    order_no = models.CharField(verbose_name='单号', max_length=24, blank=True, null=True)
    employee = models.ForeignKey(Employee, verbose_name='员工', related_name="bills", on_delete=models.DO_NOTHING, null=True, db_constraint=False)
    customer = models.ForeignKey(Customer, verbose_name='客户', related_name="customer_bills", on_delete=models.DO_NOTHING, blank=True, null=True, db_constraint=False)
    acc_title = models.ForeignKey(AccountTitle, verbose_name='科目', on_delete=models.SET_NULL, null=True, db_constraint=False)
    account_type = models.ForeignKey(Bank, verbose_name='账号', on_delete=models.SET_NULL, null=True, blank=True,
                                     db_constraint=False)
    money = models.FloatField(verbose_name='金额', default=0, blank=True, null=True)
    repayment = models.FloatField(verbose_name='还款金额', default=0, blank=True, null=True)
    order_time = models.DateField(verbose_name='时间', blank=True, null=True)
    category = models.IntegerField(verbose_name='类型', blank=True, null=True, choices=CATEGORY)
    desc = models.CharField(verbose_name='备注', max_length=100, blank=True, null=True)
    source = models.CharField(verbose_name='来源', max_length=100, blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='经手人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.order_no

    class Meta:
        verbose_name = '资金账单'
        verbose_name_plural = verbose_name
        ordering = ["-create_at"]

    @classmethod
    def get_max_code(cls, category):
        # 费用单
        if category == 0:
            year = datetime.datetime.now().strftime('FY%Y%m')
        # 其他收入单
        elif category == 1:
            year = datetime.datetime.now().strftime('QT%Y%m')
        # 借入
        elif category == 2:
            year = datetime.datetime.now().strftime('B%Y%m')
        # 借出
        elif category == 3:
            year = datetime.datetime.now().strftime('L%Y%m')
        else:
            year = datetime.datetime.now().strftime('FY%Y%m')

        max_code = cls.objects.filter(order_no__startswith=year).aggregate(max_code=Max("order_no"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(year, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(year, num)
            return code

    def save(self, *args, **kwargs):
        if not self.order_no:
            order_no = self.__class__.get_max_code(self.category)
            self.order_no = order_no
        return super().save(*args, **kwargs)


class RepaymentBill(models.Model):
    """还款记录"""
    order_no = models.CharField(verbose_name='单号', max_length=24, blank=True, null=True)
    bill = models.ForeignKey(FundBill, verbose_name='借入借出', related_name='repayments', on_delete=models.CASCADE, blank=True, null=True, db_constraint=False)
    bill_date = models.DateField(verbose_name='还款时间', blank=True, null=True)
    money = models.FloatField(verbose_name='还款金额', blank=True, null=True)
    desc = models.CharField(verbose_name='备注', max_length=100, blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='经手人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.order_no

    class Meta:
        verbose_name = '还款记录'
        verbose_name_plural = verbose_name
        ordering = ["-create_at"]

    @classmethod
    def get_max_code(cls):
        year = datetime.datetime.now().strftime('R%Y%m')
        max_code = cls.objects.filter(order_no__startswith=year).aggregate(max_code=Max("order_no"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(year, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(year, num)
            return code

    def save(self, *args, **kwargs):
        if not self.order_no:
            order_no = self.__class__.get_max_code()
            self.order_no = order_no
        return super().save(*args, **kwargs)


class BusinessFee(models.Model):
    """商务费"""
    sale_order = models.ForeignKey(SaleOrder, verbose_name='销售单', related_name='fees', on_delete=models.CASCADE, db_constraint=False)
    name = models.CharField(verbose_name='姓名', blank=True, null=True, max_length=24)
    money = models.FloatField(verbose_name='商务费', blank=True, null=True)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '案件商务费'
        verbose_name_plural = verbose_name
        ordering = ["-id"]
